package cn.gson.crm.controller.permission;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.ResourceDao;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.Resource;
import cn.gson.crm.model.others.Result;
import cn.gson.crm.service.ResourceService;

@Controller
@RequestMapping("resource")
public class ResourceController {
	
	@Autowired
	ResourceDao rsDao;
	
	@Autowired
	ResourceService rsService;
	
	@GetMapping
	public String index() {
		return "permission/resource";
	}
	
	@RequestMapping("list")
	@ResponseBody
	public List<Resource> getList() {
		return rsService.getTreeData();
	}
	
	@RequestMapping("list/dynamic")
	@ResponseBody
	public List<Resource> getListDynamic(HttpSession session) {
		Employee employee = (Employee) session.getAttribute("employee");
		List<Resource> tree = rsService.getTreeDataByRole(employee.getRole());
		/*List<Resource> rights = employee.getRole().getResources();
//		System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
//		for(int i =0;i<tree.size();i++) {
//			System.out.println(tree.get(i));
//		}
		List<Resource> roots = new LinkedList<>();
		//找到父节点
		for(Resource r : rights) {
			if(r.getParent()==null) {
				roots.add(r);
			}
		}
		for(Resource r : roots) {
			roots.
		}
		session.setAttribute("tree", tree);*/
		return tree;
	}
	
	@RequestMapping("single")
	@ResponseBody
	public Resource single(Long id) {
		System.out.println("im gonne find " + id);
		return rsDao.findOne(id);
	}
	
	@GetMapping({ "form", "form/{id}" })
	public String getRoleForm(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("rs", rsDao.findOne(id));
		}
		return "permission/resource/form";
	}
	
	@PostMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid Resource resource, BindingResult br) {
		//检测parent是否为瞬时态，是则设为null
		if(resource.getParent().getId() == null) resource.setParent(null);
		JSONObject message = new JSONObject();
		if(br.hasErrors()) {
			message.put("error", "校验失败");
		} else {
			try {
				rsDao.save(resource);
				message.put("success", true);
			} catch (Exception e) {
				message.put("success", false);
			}
		}
		return message;
	}
	
	@PostMapping("delete/{id}")
	@ResponseBody
	@Transactional
	public boolean delete(@PathVariable(required=true) Long id) {
		try {
			rsDao.delete(id);
		} catch (Exception e){
			return false;
		}
		return true;
	}
	
	@RequestMapping({"info/{id}" })
	public String getResourceInfo(@PathVariable(required = true) Long id, Model model) {
		Resource rs = rsDao.findOne(id);
		List<Resource> ancestors = new LinkedList<>();
		Resource pointer = rs.getParent();
		while(pointer != null) {
			ancestors.add(pointer);
			pointer = pointer.getParent();
		}
		model.addAttribute("rs", rs);
		model.addAttribute("ancestors", ancestors);
		return "permission/resource/info";
	}
	
	@RequestMapping("parents")
	@ResponseBody
	public List<Resource> parents() {
		return rsService.getTreeData();
	}
	
	@RequestMapping({"exist/identify", "exist/identify/{id}"})
	@ResponseBody
	public boolean isIdentifyExiting(String identify, @PathVariable(required = false)Long id) {
		if(identify.endsWith(":")) return false;
		if(id != null) {
			if(rsDao.findOne(id).getIdentify().equals(identify)) 
				return true;
		}
		return rsDao.countByIdentify(identify) == 0;
	}
}
